<?php
/**
 * Created by JetBrains PhpStorm.
 * User: 蒋文书
 * Date: 14-12-27
 * Time: 下午8:50
 * To change this template use File | Settings | File Templates.
 */

namespace Admin\Controller;
use Think\Controller;

class AuthController extends CommonController {

    /**
     * 角色列表
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function index(){
        $list =  M('role')->select();
        $this -> assign('list', $list);
        $this -> meta_title = '角色列表';
        $this -> display();
    }

    /**
     * 添加角色
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function add(){
        if( M('role')->add($_POST)){
            $this->success('新增成功！',U('Admin/Auth/Index'));
        }
       $this->meta_title = '新增角色';
       $this->display();

    }

    /**
     * 删除角色
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function del(){
        $id = I('id',0,'intval');
        if(D('auth')->del($id)){
            $this->success('删除成功',U('Index'));
        }else{
            $this->error('删除失败！');
        }
    }


    public function edit(){
        $id = I('id',0,'intval');
        if(IS_POST){
           if(D('auth')->update()){
                $this->success('更新成功',U('Index'));
            }else{
                $this->error('更新失败！');
            }
        }else{
            $this->info = D('auth')->info($id);
        }
        $this -> meta_title = '角色编辑';
        $this->display();
    }



    /**
     * 权限配置
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function access(){
        $rid = I('rid',0,'intval');
        $field=array('id','name','title','pid');
        $list =M('node')->order('sort')->field($field)->select();
        $access =M('access')->where(array('role_id'=>$rid))->getField('node_id',true);
        $list=node_merge($list,$access);
        $this -> rid = $rid;
        $this -> assign('list', $list);
        $this -> meta_title = '权限配置';
        $this -> display();

    }

    /**
     * 修改保存权限
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function addAccess(){
        $rid = I('rid',0,'intval');
        $db=M('access');
        //清空原有的权限
        $db->where(array('role_id'=>$rid))->delete();
        //组合新权限
        $data=array();
        foreach ($_POST['access'] as $v) {
            $tmp=explode('_', $v);
            $data[]=array(
                'role_id'=>$rid,
                'node_id'=>$tmp[0],
                'level'=>$tmp[1]
                );
           
        }
        //插入新权限  addAll循环插入
        if($db->addAll($data)){
            $this->success('修改成功！',U('Admin/Auth/Index'));
        }else{
            $this->error('修改失败！');
        }
        $this->meta_title = '权限配置';
        $this->display('index');

    }
    

}